package chapter5_基础构建模块.Executor.为任务设置超时;

import java.util.concurrent.*;

/**
 * 获取广告显示，如果超时则显示默认广告
 */
public class RenderPageWithAd {
    private final ExecutorService exec = Executors.newScheduledThreadPool(1);
    private static final Ad DEFAULT_AD = new Ad();
    public static final long TIME_BUDGET = 1000;

    Page renderPageWithAd() throws InterruptedException {
        long endNanos = System.nanoTime() + TIME_BUDGET;
//        执行一组task任务，返回也是按照invokeAll提交的顺序进行返回
//        exec.invokeAll();
        Future<Ad> f = exec.submit(new FetchAdTask());
        //在等待广告的同时显示页面
//        Page page = renderPageBody();
        Ad ad;
        try {
            //只等待指定的时间长度
            long timeLeft = endNanos - System.nanoTime();
            ad = f.get(timeLeft, TimeUnit.NANOSECONDS);
        } catch (ExecutionException e) {
            ad = DEFAULT_AD;
        } catch (TimeoutException e) {
            ad = DEFAULT_AD;
            f.cancel(true);
        }
//        page.setAd(ad);
//        return page;
        return null;
    }
}

class FetchAdTask implements Callable<Ad> {

    @Override
    public Ad call() throws Exception {
        return null;
    }
}

class Ad {

}
class Page {
}
